/**
 * DataTables
 */
(function (window, Ifonly) {
    //默认配置
    var defaultOptions = {
        "c_filter": false,

        //特性配置
        "serverSide": true,         //是否开启服务器模式
        "jQueryUI": false,          //控制是否使用jquerui的样式（需要引入jqueryui的css）
        "stateSave": false,          //是否开启本地缓存
        "deferRender": true,        //控制表格的延迟渲染，可以提高初始化的速度。
        "processing": true,         //是否显示正在处理的状态。
        "paging": true,           //是否开启本地分页
        "ordering": false,          //是否允许DataTable开启排序
        "info": true,          //控制是否显示表格左下角的信息
        "searching": true,         //是否允许DataTable开启搜索
        "lengthChange": true,         //是否允许最终用户改变表格每页显示的记录数
        "dom": '<"top"f>tr<"bottom"lpi><"clear">',
        //选项配置
        "lengthMenu": [10, 25, 50, 75, 100],   //定义在每页显示记录数的select中显示的选项
        "pagingType": "full_numbers",           //分页类型

        "autoWidth": false,
        "pageLength": 10,
        "ajax": {
            "url": "",
            "type": "GET"
        },
        "language": {
            "decimal": "",
            "emptyTable": "暂无数据...",
            "info": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
            "infoEmpty": "没有找到记录",
            "infoFiltered": "(从 _MAX_ 条记录过滤)",
            "infoPostFix": "",
            "thousands": ",",
            "lengthMenu": "每页 _MENU_ 条记录",
            "loadingRecords": "数据加载中...",
            "processing": "数据处理中...",
            "search": "搜索: ",
            "zeroRecords": "没有找到记录",
            "paginate": {
                "first": "<<",
                "last": ">>",
                "next": ">",
                "previous": "<"
            },
            "aria": {
                "sortAscending": ": 升序排序",
                "sortDescending": ": 降序排序"
            }
        }
    };

    function DataTable(opts, selector, params) {
        params = params || {};
        if (params["lightbox2"]) {
            lightbox.option({
                'resizeDuration': 200,
                'wrapAround': true
            });
        }
        opts = opts || {};
        selector = selector || '#data-table';
        var options = $.extend(true, {}, defaultOptions, opts);

        //处理查询条件自定义,不启用 DataTable 自带的
        if (options['c_filter'] === true) {
            if (typeof options.ajax === 'string') {
                options.ajax = {
                    "url": options.ajax,
                    "data": function (d) {
                        d['c_filter'] = options['c_filter'];
                    }
                }
            } else if (typeof options.ajax === 'object') {
                var data = options.ajax.data;
                if (data) {
                    options.ajax.data = function (d) {
                        d['c_filter'] = options['c_filter'];
                        data(d);
                    }
                } else {
                    options.ajax.data = function (d) {
                        d['c_filter'] = options['c_filter'];
                    }
                }
            }

            //绑定点击时间
            $('#search').on('click', function (e) {
                e.stopPropagation();
                e.preventDefault();
                $dt.ajax.reload();
            });
            $('#cancel').on('click',function(e) {
                $(options['searchForm'] || '#search-form').find('input[type="hidden"]').val('');
                $(options['searchForm'] || '#search-form')[0].reset();
                e.stopPropagation();
                e.preventDefault();
                $dt.ajax.reload();
            });

            //处理查询条件
            options.serverParams = options.serverParams || function (data) {
                var params = $(options['searchForm'] || '#search-form').serializeObject();
                $.each(params, function (k, v) {
                    data[k] = v;
                });
            };
        }

        var $dt = $(selector).DataTable(options);

        $(selector).on('click', '.dt-ajax', function (e) {
            e.stopPropagation();
            e.preventDefault();
            var url = $(this).attr('data-href');
            var tip = $(this).attr('data-tip') || '您是否要执行' + ($(this).text() || '该') + '操作?';
            if (url) {
                Ifonly.Notification.confirm(tip, function () {
                    Ifonly.Service.get(url, {}, function (rets) {
                        Ifonly.Notification.alert(rets.message);
                        $dt.ajax.reload();
                    });
                });
            }
        }).on('click', 'input[name="dt_check_all"]', function (e) {
            var checked = $(this).is(":checked");
            $('input[name="dt_check_value"]', selector).each(function () {
                $(this).prop('checked', checked);
            });
        });

        return $dt;
    }

    if (Ifonly) {
        Ifonly.DataTable = DataTable;
    } else {
        window.DataTable = DataTable;
    }

    var DTKit = (function () {
        return {
            auto: {
                data: null,
                width: '60px',
                defaultContent: 1,
                render: function (data, type, full, meta) {
                    return meta && meta.row !== undefined ? meta.row + 1 : "";
                },
                orderable: false,
                searchable: false,
                title: '序号',
                targets: 0
            },
            checkbox: function (render) {
                render = render || 'id';
                var key = 'id';
                if (!(typeof render == 'function')) {
                    if (typeof render == 'string') {
                        key = render;
                    }
                    render = function (data, type, full, meta) {
                        return '<input type="checkbox" class="minimal" name="dt_check_value" value="'+ full[key] +'">';
                    };
                }

                return {
                    data: null,
                    width: '60px',
                    defaultContent: 1,
                    render: render,
                    orderable: false,
                    searchable: false,
                    title: '<input type="checkbox" class="minimal" name="dt_check_all" value="all">',
                    targets: 0
                }
            },
            render: function(selector, handle) {
                selector = selector || '#data-table-action';
                var template = Handlebars.compile($(selector).html());
                return function (data, type, full, meta) {
                    handle && handle(full);
                    return template(full);
                }
            }
        }
    })();

    if (Ifonly) {
        Ifonly.DTKit = DTKit;
    } else {
        window.DTKit = DTKit;
    }

})(window, Ifonly);
